function getCurrentPageConfig(platformConfig) {
    const { href: currentUrl } = window.location;

    // 遍历所有页面配置，找到匹配的页面类型
    return platformConfig.pages.find((page) => {
        const { urlPattern, domSelector } = page.condition;
        // 匹配 URL 规则
        const urlMatched = urlPattern && new RegExp(urlPattern.replace('*', '.*')).test(currentUrl);
        // 匹配 DOM 特征
        const domMatched = domSelector && document.querySelector(domSelector);
        return urlMatched || domMatched;
    });
}

// 初始化
const currentPageConfig = getCurrentPageConfig(TAOBAO_CONFIG);
if (currentPageConfig) {
    initCollector(currentPageConfig);
}

function initCollector(pageConfig) {
    const { cardSelector, extractor, buttonStyle } = pageConfig;
    // 监听 DOM 变化
    const observer = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            mutation.addedNodes.forEach((node) => {
                if (node.nodeType === Node.ELEMENT_NODE) {
                    const cards = node.matches(cardSelector)
                        ? [node]
                        : node.querySelectorAll(cardSelector);
                    cards.forEach((card) => addButton(card, extractor, buttonStyle));
                }
            });
        });
    });

    observer.observe(document.documentElement, { childList: true, subtree: true });

    // 初始处理已有卡片
    document.querySelectorAll(cardSelector).forEach((card) => addButton(card, extractor, buttonStyle));
}

function addButton(card, extractor, buttonStyle) {
    if (card.dataset.hasButton) return;
    card.dataset.hasButton = "true";

    const btn = document.createElement("button");
    btn.textContent = "采集";
    Object.assign(btn.style, {
        ...TAOBAO_CONFIG.common.buttonStyle,
        ...buttonStyle, // 应用页面特定样式
    });

    // 鼠标悬停显示按钮
    // card.addEventListener("mouseenter", () => (btn.style.display = "block"));
    // card.addEventListener("mouseleave", () => (btn.style.display = "none"));

    // 点击采集信息
    btn.addEventListener("click", async (e) => {
        e.preventDefault();
        e.stopPropagation();
        try {
            // 显示加载提示
            showMessage("正在采集商品规格...", true);
            const productInfo = await extractor(card);
            // chrome.runtime.sendMessage({ action: "collect", data: productInfo });
            console.log('productInfo=========', productInfo);
            // 显示成功提示（3秒后自动关闭）
            showMessage("采集成功！", true);
            setTimeout(hideMessage, 1500);
        } catch (error) {
            // 显示失败提示
            showMessage("采集失败，请重试！失败原因:" + error, false);
            setTimeout(hideMessage, 3000);
        }
    });

    card.style.position = "relative";
    card.appendChild(btn);
}
